<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//业务收入
class Income extends CommonController {

	function __construct(){
		
		parent::__construct();
		$this->load->model('Chuna/cashiersModel','CurModel');
		
		$this->load->model('Chuna/CashBalanceModel','CashBalanceModel');
	}
	
	
	//start
	/**
	* @name 获取列表
	* @param page ture char 页面
	* @param size ture char 数量
	* @return 成功返回1
	*/
	//end
	function get_list(){
		$user_id = $this->user_id;
		
		
		if(!$this->check_priv('chuna_yewu|chuna_yewu_1')){
			$this->err_out(LANG_NOPRIV);
		}


		$page = $this->input->post('page',null,1);
		$size = $this->input->post('size',null,10);
		
		$filter = $this->input->post('f',null,array());

		
		if(empty($filter['date_month'])){
			$this->err_out('请选择月份');
		}
		else{
			$filter['date_month'] = date('Y-m',strtotime($filter['date_month'].'-01'));
		}
		if(empty($filter['company'])){
			$this->err_out('请选择公司主体');
		}
		$fg = explode(',',$filter['company']);
		
		if(!isset($filter['xList']) || count($filter['xList'])<=0){
			$this->err_out('请选择科目');
		}
		
		$arr = array();
		
		foreach($fg as $val){
			$ls_arr = array(
				'company'=>$val,
				'date_month'=>$filter['date_month'],
				'is_del' => 0
			);
			if(isset($filter['bz'])){
				$ls_arr['bz'] = $filter['bz'];
			}
			
			$ddd = $this->get_subject_cl($filter['xList'],$ls_arr);
			
			$arr[] = array(
				'name'=>$val,
				'data'=>$ddd
			);
		}
		$tlist = array();
		
		
		$tmonth = array('custom_name'=>'本月合计');
		foreach($arr as $key=>$val){
			$ddd = $val['data'];
			foreach($ddd['total_month'] as $k=>$v){
				if(isset($tmonth[$k])){
					$tmonth[$k] += floatVal($v);
				}
				else{
					$tmonth[$k] = floatVal($v);
				}
			}
		}
		$tmonth['is_total'] = 1;
		$tlist[] = $tmonth;
		
		$tyear = array('custom_name'=>'本年累计');
		foreach($arr as $key=>$val){
			$ddd = $val['data'];
			foreach($ddd['total_year'] as $k=>$v){
				if(isset($tyear[$k])){
					$tyear[$k] += floatVal($v);
				}
				else{
					$tyear[$k] = floatVal($v);
				}
			}
		}
		$tyear['is_total'] = 1;
		$tlist[] = $tyear;
		
		
		$total = array(
			'list'=>$tlist
		);
		
		
		$data = array(
			'list'=>$arr,
			'total'=>$total
		);
		$this->data_out($data);
	}
	
	function get_subject_cl($clist,$ls_arr=array()){
		$arr = array();
		$colnmns = array();
		$list = array();
		$total_month = array();
		$total_year = array();

		//$colnmns['bz'] = '币种';
		
		foreach($clist as $key=>$val){
			$name = 'subject'.$key;
			$colnmns[$name] = $val;
			
			
			$ls_arr['subject'] = trim($val);
			//加入能看的主体公司权限
			//$ls_arr['company_ids'] = $this->querys;
			
			$res = $this->CurModel->get_all($ls_arr);
			$total_m = 0;
			foreach($res as $k=>$row){
				$ls_data = array();
				$ls_data[$name] = $row['money'];
				$ls_data['id'] = $row['id'];
				$ls_data['custom_name'] = $row['custom_name'];
				$ls_data['remarks'] = $row['remarks'];
				$ls_data['money'] = $row['money'];
				$ls_data['type'] = $row['type'];
				$ls_data['mtype'] = $row['mtype'];
				$ls_data['date_month'] = $row['date_month'];
				$ls_data['company'] = $row['company'];
				$ls_data['info'] = $row['info'];
				$ls_data['date'] = $row['date'];
				$ls_data['region'] = $row['region'];
				$ls_data['subject'] = $row['subject'];
				$ls_data['bumen'] = $row['bumen'];
				$ls_data['bumen_scale'] = $row['bumen_scale'];
				$ls_data['bz'] = $row['bz'];
				
				$list[] = $ls_data;
				$total_m += floatval($row['money']);
				
			}
			
			$total_month[$name] = $total_m;
			
			$total = $this->CurModel->get_year_total($ls_arr);
			
			$total_year[$name] = $total?$total:0;
		}
		/*
		foreach($list as $key=>$val){
			$mm = 0;
			foreach($val as $v){
				$mm += floatval($v);
			}
			$list[$key]['total'] = $mm;
		}
		*/
		
		$arr['colnmns'] = $colnmns;
		$arr['list'] = $list;
		$arr['total_month'] = $total_month;
		$arr['total_year'] = $total_year;
		
		
		
		return $arr;
	}
	
	
	//start
	/**
	* @name 编辑数据
	* @param id ture int ID
	* @param custom_name ture char 客户名称
	* @param remarks ture char 备注
	* @return 成功返回1
	*/
	//end
	function edit_data(){
		
		if(!$this->check_priv('chuna_yewu_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$user_id = $this->user_id;
		$id = $this->input->post('id',null,0);
		
		$info = $this->CurModel->_id_get_info($id);
		if(!$info){
			$this->err_out('数据不存在');
		}
		
		$arr = array(
			'custom_name'=>$this->input->post('custom_name',null,''),
			'remarks'=>$this->input->post('remarks',null,''),
		);

		//可编辑金额
		$money = $this->input->post('money',null,'');
		$mtype = $this->input->post('mtype');
		$date_month = $this->input->post('date_month');
		if($money){
			$arr['money'] = $money;
			$balance = $this->get_balance($date_month,$id);
			if($mtype == 1){
				$arr['expenses'] = $money;
				$arr['balance'] = $balance - $money;
			}else{
				$arr['income'] = $money;
				$arr['balance'] = $balance + $money;
			}
		}
		
		$this->CurModel->edit($arr,"id='{$id}'");
		
		$this->data_out(1);
	}

	function get_balance($date_month,$id=''){
		
		$prev = $this->CashBalanceModel->get_prev_balance($date_month);
		if($prev){
			$prev_money = $prev['money'];
		}
		else{
			$prev_money = 0;
		}

		$arr = $id?array('date_month'=>$date_month,'currentID'=>$id):array('date_month'=>$date_month);
		
		$income = $this->CurModel->get_totals($arr,'income');
		$expenses = $this->CurModel->get_totals($arr,'expenses');
		
		$money = $prev_money + $income - $expenses;
		
		return $money;
	}
	
	//start
	/**
	* @name 导出数据
	* @return 成功返回1
	*/
	//end
	function export_data(){
		
		if(!$this->check_priv('chuna_yewu|chuna_yewu_1')){
			$this->err_out(LANG_NOPRIV);
		}
		
		
		$user_id = $this->user_id;
		
		$name = $this->input->post('name',null,'');
		$columns = $this->input->post('columns',null,array());
		$list = $this->input->post('list',null,array());
		
		$arr = array();
		
		$arr['A1'] = $name;
		$index = 0;//$this->data_out($columns);exit;
		foreach($columns as $key=>$val){
			$col = $this->get_char($index,'A');
			$arr[$col.'2'] = $val;
			
			foreach($list as $k=>$item){
				
				$arr[$col.($k+3)] = isset($item[$key])?$item[$key]:'';
			}
			
			$index++;
		}
		
		
		$result = $this->Excel_write($arr);
		if(!$result){
			$this->err_out('生成Excel文件失败');
		}
		
		$url = base_url($result);
		
		$this->data_out($url);
	}
	
	//start
	/**
	* @name 导出所有数据
	* @return 成功返回1
	*/
	//end
	function export_all(){
		if(!$this->check_priv('chuna_yewu|chuna_yewu_1')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$user_id = $this->user_id;
		
		$columns = $this->input->post('columns',null,array());
		$mlist = $this->input->post('list',null,array());
		$totals = $this->input->post('totals',null,array());
		
		$arr = array();
		$ls_index = 1;
		foreach($mlist as $ind=>$row){
			$arr['A'.$ls_index] = $row['name'];
			$ls_index++;
			
			$list = $row['list'];
			$index = 0;
			foreach($columns as $key=>$val){
				$col = $this->get_char($index,'A');
				$arr[$col.($ls_index)] = $val;
				$index++;
			}
			$ls_index++;
			
			
			foreach($list as $k=>$item){
				$index = 0;
				
				foreach($columns as $key=>$val){
					$col = $this->get_char($index,'A');
					
					$arr[$col.($ls_index)] = isset($item[$key])?$item[$key]:'';
					$index++;
				}
				$ls_index++;
			}
		}
		
		//计算总收入
		$arr['A'.$ls_index] = '总收入';
		$ls_index++;
		$index = 0;
		foreach($columns as $key=>$val){
			$col = $this->get_char($index,'A');
			$arr[$col.($ls_index)] = $val;
			$index++;
		}
		$ls_index++;
		foreach($totals as $k=>$item){
			$index = 0;
			
			foreach($columns as $key=>$val){
				$col = $this->get_char($index,'A');
				
				$arr[$col.($ls_index)] = isset($item[$key])?$item[$key]:'';
				$index++;
			}
			$ls_index++;
		}
		
		
		
		
		$result = $this->Excel_write($arr);
		if(!$result){
			$this->err_out('生成Excel文件失败');
		}
		
		$url = base_url($result);
		
		$this->data_out($url);
	}
	
	function get_char($num,$pos='A'){
		if($num==0){
			return $pos;
		}

		for($i=0;$i<$num;$i++){
			$pos++;
		}
		return $pos;
	}
	
	function Excel_write($data,$merges=array()){
		$this->load->library('PHPExcel');
		
		// 创建Excel文件对象
		$objPHPExcel = new PHPExcel();
		// 设置文档信息，这个文档信息windows系统可以右键文件属性查看
		$objPHPExcel->getProperties()->setCreator("作者lalala")
			->setLastModifiedBy("最后更改者")
			->setTitle("文档标题")
			->setSubject("文档主题")
			->setDescription("文档的描述信息")
			->setKeywords("设置文档关键词")
			->setCategory("设置文档的分类");
		
		$objPHPExcel->setActiveSheetIndex(0);

		
									
		
		$objPHPExcel->getActiveSheet()->getStyle('A3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('B3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		
		foreach($data as $key=>$val){
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($key,$val);
		}
		
		foreach($merges as $key=>$val){
			$objPHPExcel->setActiveSheetIndex(0)->mergeCells($val);
		}
		
		$objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel ->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(0))->setAutoSize(true); 
		//$objPHPExcel->getActiveSheet()->setTitle('第一个sheet');

		// 设置第一个sheet为工作的sheet
		

		// 保存Excel 2007格式文件，保存路径为当前路径，名字为export.xlsx
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$time = time();
		$dir  =  'upload/res/upload/other/'.date('Ymd');
		if(!is_dir(FCPATH . $dir)){
			@mkdir(FCPATH . $dir);
		}
		
		$file_name = $time.'_'.rand(10000,99999).'.xlsx';
		$objWriter->save(FCPATH . $dir .'/' .$file_name);
		
		return $dir .'/' .$file_name;
	}
}
